﻿using DevExpress.XtraBars.Ribbon;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Instrument;
using System.Configuration;

namespace UI
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int IParam);
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;
        [DllImport("user32")]
        private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, IntPtr lParam);
        private const int WM_SETREDRAW = 0xB;

        public Employee CurrentOperator;

        private void Login_MouseDown(object sender, MouseEventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
            {
                ReleaseCapture();
                SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
            }
        }

        private void Login_Load(object sender, EventArgs e)
        {
            UserNameTxtEdit.Text = ConfigurationManager.AppSettings["User"];
            PassWordTxtEdit.Text = ConfigurationManager.AppSettings["PassWord"];

        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            string userName = UserNameTxtEdit.Text;
            string passWord = PassWordTxtEdit.Text;
            var dataBaeOperation = DataBaseOperation.GetInstance();
            Employee employee = dataBaeOperation.MatchUserID(userName, passWord);
            if(employee != null)
            {
                CurrentOperator = employee;
                this.DialogResult = DialogResult.OK;    //返回一个登录成功的对话框状态
                this.Close();    //关闭登录窗口
            }
            else
            {
                MessageBox.Show("用户名或密码有误，请重新输入");
            }
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void Login_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (CurrentOperator == null)
                return;
            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            configuration.AppSettings.Settings["User"].Value = CurrentOperator.JobNum;
            configuration.AppSettings.Settings["PassWord"].Value = CurrentOperator.PassWord;
            configuration.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("AppSettings");
        }
    }
}
